package com.danke.lib.pay;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;

import org.json.JSONException;
import org.json.JSONObject;

import androidx.fragment.app.Fragment;

/**
 * 蛋壳支付
 *
 * <pre class="prettyprint">
 * {
 *     "payType":1, # 1微信 2支付宝 3招行一卡通
 *     "credentialMap":{
 *         # 微信
 *         "appId":"wx123",
 *         "partnerId":"12345",
 *         "prepayId":"wxabcde",
 *         "nonceStr":"4ab2ddcc",
 *         "timeStamp":"1544096906",
 *         "packageValue":"Sign=WXPay",
 *         "sign":"12345ASDFGHJ",
 *
 *         # 支付宝
 *         "orderInfo":"app_id=2015121000952778&method=alipay.trade.app.pay&format=JSON&charset=utf-8&sign_type=RSA×tamp=2018-12-13%2019%3A06%3A41&version=1.0&biz_content=%7B%22body%22%3A%22%E6%90%AC%E5%AE%B6%E5%AE%9A%E9%87%91%22%2C%22subject%22%3A%22%E6%90%AC%E5%AE%B6%E5%AE%9A%E9%87%91%22%2C%22out_trade_no%22%3A%2210000465%22%2C%22total_amount%22%3A0.01%2C%22product_code%22%3A%22QUICK_MSECURITY_PAY%22%2C%22disable_pay_channels%22%3A%22coupon%2Cpromotion%2Cvoucher%2Cpoint%2Cmdiscount%2Ccredit_group%22%2C%22timeout_express%22%3A%2259m%22%7D¬ify_url=https%3A%2F%2Fnotify.pingxx.com%2Fnotify%2Fcharges%2Fch_mD4if9CiPqbPmj1Gy1vDqbzT&sign=DVALObELu5FBG5V7sBWWLmMxVgCx6ZcMoI4FbWId%2Bxp6KMqGsEJmzi1vV3Qg9%2BZlMqjWOJsy%2B5OSrucFH1%2Fhgz%2Bxgs4Tivm0dI4bYbQ4nrZixWuQGnCZPdDj3J9GMpiOZfVBKVqsnk4HiO15MSo2hEXD42h24UK2gsWGDM2GvVM%3D"
 *
 *         # 招行一网通
 *         "jsonRequestData": {
 * 		       "version": "1.0",
 * 		       "sign": "558418c28b944b274bed327b2bc97fbdd37e8a70e9db9552c25e8d413b320bca",
 * 		       "signType": "SHA-256",
 * 		       "reqData": {
 * 		           "dateTime": "20190119194844",
 * 		           "branchNo": "0010",
 * 		           "merchantNo": "630316",
 * 		           "date": "20190119",
 * 		           "orderNo": "Charge1383909T1547898523",
 * 		           "amount": "50.00",
 * 		           "expireTimeSpan": "30",
 * 		           "payNoticeUrl": "https://notify.pingxx.com/notify/charges/ch_nPCyXPiPKy1OHGG0uPvfvnXP",
 * 		           "payNoticePara": "ch_nPCyXPiPKy1OHGG0uPvfvnXP",
 * 		           "clientIP": "99.12.43.61",
 * 		           "cardType": "",
 * 		           "subMerchantNo": "",
 * 		           "subMerchantName": "",
 * 		           "subMerchantTPCode": "",
 * 		           "subMerchantTPName": "",
 * 		           "payModeType": "",
 * 		           "agrNo": "6",
 * 		           "merchantSerialNo": "6",
 * 		           "userID": "6",
 * 		           "lon": "30.949505",
 * 		           "lat": "50.949506",
 * 		           "riskLevel": "",
 * 		           "extendInfo": "",
 * 		           "extendInfoEncrypType": "RC4"
 *             }
 *         },
 * 		   "ChannelUrl": "https://netpay.cmbchina.com/netpayment/BaseHttp.dll?MB_EUserPay",
 * 		   "channelVersion": "2.0"
 *     }
 * }
 * </pre>
 *
 * @author wupuquan
 * @version 1.0
 * @since 2018/12/28 17:26
 */
public class DKPay {

    private static final String TAG = "DKPay";
    public static final int REQUEST_CODE_PAY = 9527;
    public static boolean DEBUG = false;

    /**
     * 调起支付
     *
     * @param activity activity
     * @param charge   支付数据
     */
    public static void launch(Activity activity, String charge) {
        launch(activity, null, charge);
    }

    public static void launch(Fragment fragment, String charge) {
        launch(null, fragment, charge);
    }

    private static void launch(Activity activity, Fragment fragment, String charge) {
        if (TextUtils.isEmpty(charge)) {
            return;
        }
        if (fragment != null) {
            activity = fragment.getActivity();
        }
        if (activity == null) {
            return;
        }
        try {
            JSONObject jsonObject = new JSONObject(charge);
            String payType = jsonObject.optString("payType");
            // 微信支付
            if (TextUtils.equals(DKPayChannel.WX.getChannel(), payType)) {
                String packageName = activity.getPackageName();
                Intent intent = new Intent();
                ComponentName component = new ComponentName(packageName, packageName + ".wxapi.WXPayEntryActivity");
                intent.setComponent(component);
                intent.putExtra(DKPayActivity.EXTRA_CHARGE, charge);
                if (fragment != null) {
                    fragment.startActivityForResult(intent, REQUEST_CODE_PAY);
                } else {
                    activity.startActivityForResult(intent, REQUEST_CODE_PAY);
                }
                return;
            }
        } catch (JSONException e) {
            e.printStackTrace();
            return;
        } catch (ActivityNotFoundException e) {
            e.printStackTrace();
            Log.e(TAG, "请检查AndroidManifest.xml中是否注册了 包名.wxapi.WXPayEntryActivity的类");
            return;
        }

        // 其他支付
        if (fragment != null) {
            DKPayActivity.startForResult(fragment, charge, REQUEST_CODE_PAY);
        } else {
            DKPayActivity.startForResult(activity, charge, REQUEST_CODE_PAY);
        }
    }

    public static void debug(boolean debug) {
        DKPay.DEBUG = debug;
    }
}
